<?php
	include_once("backend/constant.php");
	
	$connection = new mysqli(dbhost, dblogin, dbpwd, database) or	die("Couldn't connect to database!");
	$connection->set_charset("utf8");	
	session_start();
	$pageView = 1;
	$sql = "select p_value from settings where p_name='pageview'";
	$result = $connection->query($sql) or die("Query failed select!");
	if($result!=false && $row=$result->fetch_assoc()){
		$pageView = $row["p_value"];
	}
	
	if(isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
		// last request was more than 30 minutes ago
		session_unset();     // unset $_SESSION variable for the run-time 
		session_destroy();   // destroy session data in storage
		
		if($pageView==1){
			$sql = "insert into settings(p_name, p_value) values('pageview', '" . $pageView . "')";
		}else{
			$pageView++;
			$sql = "update settings set p_value='" . $pageView . "' where p_name='pageview'";
		}
		$connection->query($sql) or die("Query failed!");
		
	}
	$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
	$_SESSION["page"]='article.php?id=' . $_GET["id"];
	$articleId = $_GET["id"];
	//$threadId = $connection->thread_id;
	$postLst = $connection->query("select a.id,u.username,a.createdDate,title_vn,abstract,content_vn,content_en,nview,
		a.tag from articles as a inner join users as u on a.userId=u.id where a.id=" . $articleId) or die("Query get article failed!");
	$comentList = $connection->query("select content, u.username, c.fullname, c.createdDate, c.active 
		from comments as c left join users as u on c.userId = u.id
		where article=" . $articleId) or die("Query Failed!");
	$fileList = $connection->query("select filename from media where active=1 AND article=" . $articleId) or die("Query get comment Failed!");
	
?>
<!DOCTYPE HTML>
<html>
	<head>
		<meta charset="utf-8">
		<link rel="stylesheet" type="text/css" href="styles.css"/>
		<link rel="stylesheet" type="text/css" href="css/sourcecode.css"/>
		<script type='text/javascript' src='jquery-min.js'></script>
		<script type="text/javascript">
			$(document).ready(function(){
				$("#btnLogin").click(function(){
					var username = document.getElementById("txtUsername").value;
					var pwd = document.getElementById("txtPassword").value;
					if(username.length <= 0){
						alert("Username cannot be blank");
						return false;
					}
					/*
					$.ajax({
						url:"backend/user.php",
						cache:false,
						type:'POST',
						data:{ACTION:'LOGIN',txtUsername:username,txtPassword:pwd},
						success:function(responseText){
							var rs = $.parseJSON(responseText);
							$('#div_login').fadeOut();
							$('#div_user_pane').hide().html("Login").fadeIn();
						}
					});
					*/
					$("#frmLogin").submit();
					return false;
				});
				
				$("#btnReg").click(function(){
					window.location.replace("reg.php");
					/*
						OR we can use
						window.location.href = "";
					*/
				});
				
				$("#btnLogout").click(function(){
					
					$.ajax({
						url:"backend/user.php",
						cache:false,
						type:'POST',
						data:{ACTION:'LOGOUT'},
						success:function(responseText){
							/*var rs = $.parseJSON(responseText);
							$('#div_user_pane').fadeOut();
							$('#div_login').fadeIn();*/
							window.location.replace("index.php");
						}
					});
					
					return false;
				});
				
				$("#btnPostComment").click(function(){
					var cmm = $("#txtComment").val();//document.getElementById("txtComment").value;
					var fullname = $("#txtFullname").val();
					var userid = $("#hUserId").val();
					
					if(fullname=="" && userid<=0){
						alert("You are neither logged in nor provided a fullname. Please login or provide your fullname.");
						return false;
					}
					
					if(cmm==""){
						alert("The content of comment can not be blank.");
						return false;
					}
					
					$.ajax({
						url:"backend/post.php",
						cache:false,
						type:'POST',
						data:{ACTION:'COMMENT',article:<?php print $articleId;?>,txtContent:cmm,txtFullname:fullname},
						success:function(responseText){
							//alert(responseText);
							var rs = $.parseJSON(responseText);
							if(rs.status == "OK"){
								var cdiv = document.getElementById("comment_div");
								var newComment = document.createElement("div");
								
								if(userid>0)
									newComment.innerHTML = '<b> <?php print isset($_SESSION["loggedUser"])?$_SESSION["loggedUser"]:'';?> </b>: ' + cmm;
								else
									newComment.innerHTML = '<b>' + fullname +  '</b>: ' + cmm;
								
								cdiv.appendChild(newComment);
								cdiv.appendChild(document.createElement("br"));
								document.getElementById("txtComment").value = "";
							}else{
								alert(responseText);
							}
						}
					});
					return false;
				});
				
				$("input:radio[name=language]").change(function(){
					var lang = $(this).val();
					$.ajax({
						url:"backend/post.php",
						cache:false,
						type:'POST',
						data:{ACTION:'LANGUAGE',article:<?php print $articleId;?>,language:lang},
						success:function(responseText){
							
							$("#div-content").html(responseText);
							/*
							var rs = $.parseJSON(responseText);
							if(rs.status == "OK"){
								$("#div-content").html(rs.content);
							}
							*/
						}
					});
					return false;
				});
			});
			
		</script>
		
		<title>VTech blog - A technical blog</title>
	</head>
	<body>
		<div id="container">
			<div id="div_header">
				<?php 
					if( !isset($_SESSION["loggedUser"]) || $_SESSION["loggedUser"]==null){ ?>
				<div id="div_login">
					<form id="frmLogin" name="frmLogin" method="post" action="backend/login.php">
						<div style="float:left;width:120px;">
							<input type="hidden" name="ACTION" value="LOGIN" /> 
							<input style="width:79%;margin: 2px 25px;" type="text" class="loginText" id="txtUsername" name="txtUsername" value="" />
						</div>
						<div style="float:left;width:120px;">
							<input style="width:95%;margin: 2px 5px;" type="password" class="loginText" id="txtPassword" name="txtPassword" value="" />
						</div>
						<div style="float:left;padding-left:5px;vertical-align:middle;">
							<a href="#" style="text-decoration:none;color:#dafafa;" id="btnLogin">login</a> or <a style="text-decoration:none;color:#dafafa;" id="btnReg" href="#">sign up</a>
						</div>
					</form>
				</div>
				<?php }else{ ?>
					<div id="div_user_pane">
						<span style="padding-left:30px;color:#dafafa;">Xin chao </span>
						<a href="#" style="text-decoration:none;color:#ffff22;" ><span style="font-weight:bold;"><?php echo $_SESSION["loggedUser"]; ?></span></a>
						<a href="#" style="text-decoration:none;color:#ffdada" id="btnLogout">Logout</a>
					</div>
				<?php } ?>
			</div>
			<div id="div_nav" class="menu">
				<?php include "nav_bar.php" ?>
			</div>
			<div id="sidebar">
				<div>
					<?php
						$result = $connection->query("select id, title_vn from articles where active=1 order by nview desc limit 5") or die("Query failed select!");
						if($result != false){
							print "<ul class=\"popular-post\">";
							while($row = $result->fetch_assoc()){
								print "<li><a href=\"#\" id=\"post{$row["id"]}\" >" . $row["title_vn"] . "</a></li>";
							}
							print "</ul>";
						}
					?>
				</div>
				<div class="sidebar-tag">
					<?php
						$arrConstantTags = array(0=>'c/c++','java','javascript','uml','c#','algorithm',
						'vb','vba','linux','windows','atl','eclipse','rcp','computer-vision','php');
						$fontSize = 50;
						for($i=0;$i<count($arrConstantTags);$i++){
							$fontSize = rand(70, 100);
							print "<a href=\"#\" style=\"font-size:". $fontSize ."%;\"
							id=\"tag-item{$i}\" >" . $arrConstantTags[$i] . "</a>";
						}
					?>
				</div>
				<div id="pagehit">
					Page hits: <?php print $pageView; ?>
				</div>
			</div>
			<div id="div_main">
				<div id="div-lang">
					<label for="rdVN">Vietnamese</label>
					<input type="radio" title="Vietnamese" id="rdVN" name="language" value="0" checked />
					&nbsp;
					<label for="rdEN">English</label>
					<input type="radio" title="English" id="rdEN" name="language" value="1" />
				</div>
				<?php
					if( ($postLst != false) && ($row = $postLst->fetch_assoc()) ){
						$pageView = $row["nview"] + 1;
						$connection->query("update articles set nview=" . $pageView . " where id=" . $articleId) or die("Query update pageview failed!");
						$tags = preg_split("/,/", $row["tag"], -1, PREG_SPLIT_NO_EMPTY);
						print "<p><span class='articleTime'>" . $row["createdDate"]. " by <a href='#'><i>" . $row["username"] . "</i></a>&nbsp;" . $pageView . "&nbsp;view(s)</span></p>";
						print "<div class=\"article_title\" ><h2>" . $row["title_vn"] . "</h2></div><div><b>" . $row["abstract"] . "</b></div>
						<div id=\"div-content\">" . stripslashes($row["content_vn"]) . "</div>";
						print "<div class=\"post-tags\">";
						for($i=0;$i<count($tags);$i++){
							print "<a href=\"#\" class=\"post-tag\" >" . $tags[$i] . "</a>";
						}
						print "</div>";
					}
					
					while($row = $fileList->fetch_assoc()){
						print "<div><a href='files/" . $row["filename"]. "'>" . $row["filename"] . "</a></div>" ;
					}
					
					$connection->close();
				?>
				<hr/>
				<div class="cmmblock">
					<input type="hidden" id="hUserId" name="hUserId" value="<?php print isset($_SESSION["loggedUserId"])?$_SESSION["loggedUserId"]:0; ?>" />
					<div class="fl cmminputlb">Fullname</div><div class="cmminput"><input title="Your name here" type="text" size="40" id="txtFullname" name="txtFullname" ></input></div>
					<div class="fl cmminputlb">Email</div><div class="cmminput"><input type="text" size="40" id="txtEmail" name="txtEmail" ></input></div>
					<div id="comment-form-comment" class="">
						<textarea title="Leave your comment here..." placeholder="Leave your comment here..." cols="70" style="border:none;display:inline-block;" id="txtComment" ></textarea>
					</div>
					<input type="button" class="comment-submit" id="btnPostComment" value="Post" />
				</div>
				<hr/>
				<div id="comment_div">
				<?php
					if($comentList != false){
						while( $row = $comentList->fetch_assoc() ){
							if($row["username"]!=null)
								print "<div><b>". $row["username"]. "</b>: " . $row["content"] . "</div><br/>";
							else
								print "<div><b>". $row["fullname"]. "</b>: " . $row["content"] . "</div><br/>";
						}
					}
				?>
				</div>
			</div>
			<div id="div_footer" >Copyright 2013 @Dao Anh Vu</div>
		</div>
	</body>
</html>
